from django.shortcuts import render, redirect
from django.views import View
import re
from django import http
from django.contrib.auth import login, authenticate, logout
from django_redis import get_redis_connection
from django.conf import settings
from django.contrib.auth import mixins
import json
from django.db import DatabaseError

from .models import User, Address
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredView
from celery_tasks.email.tasks import send_verify_url
from .utils import generate_email_verify_url, check_email_verify_url
import logging
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis


logger = logging.getLogger('django')


class RegisterView(View):
    """用户注册"""

    def get(self, request):
        """展示用户注册界面"""
        return render(request, 'register.html')

    def post(self, request):
        """用户注册逻辑"""
        # 接收请求体中表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow')  # 多选框如果没有指定value勾选时传入'on'  没勾选就None

        # 校验
        # 校验必传参数是否都传递  None  False  '', [], {}
        if all([username, password, password2, mobile, sms_code, allow]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        if password != password2:
            return http.HttpResponseForbidden('输入的密码不一致')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # 短信验证码校验
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 将redis中的短信验证码获取来,
        sms_code_server_bytes = redis_conn.get('sms_%s' % mobile)
        # 短信验证码从redis获取出来之后就从redis数据库删除: 让它是一次性
        redis_conn.delete('sms_%s' % mobile)
        # 判断redis中是否获取到短信验证码(判断是否过期)
        if sms_code_server_bytes is None:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '短信验证码已过期'})
        #  从redis获取出来的数据注意类型问题
        sms_code_server = sms_code_server_bytes.decode()
        # 判断短信验证码是否填写正确
        if sms_code != sms_code_server:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '短信验证码输入错误'})

        # 新增用户记录
        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 状态保持 JWT
        # 将用户的id值存储到session中  会生成一个sessionid 存储到对应用户自己的浏览器cookie
        login(request, user)

        # 跳转到首页
        response = redirect('/')
        response.set_cookie('username', user.username, max_age=settings.SESSION_COOKIE_AGE)
        return response


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        # 从数据库查询当前username是否重复
        count = User.objects.filter(username=username).count()
        # 响应
        return http.JsonResponse({'count': count})


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        # 从数据库查询当前mobile是否重复
        count = User.objects.filter(mobile=mobile).count()
        # 响应
        return http.JsonResponse({'count': count})


class LoginView(View):
    """用户登录"""

    def get(self, request):
        """提供登录界面"""
        return render(request, 'login.html')

    """
    def post(self, request):
        #登录功能逻辑
        # 1.接收请求体表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')

        # 2.校验
        # try:
        #     user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return http
        #
        # if user.check_password(password) is False:
        #     return http
        if re.match(r'^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        # 用户登录认证
        user = authenticate(request, username=username, password=password)
        User.USERNAME_FIELD = 'username'

        # 如果登录失败
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 3.状态保持
        login(request, user)
        # 3.1 如果用户没有勾选记住登录
        # 如果session 过期时间设置为None 表示使用默认的14天, 如果设置为0 代表关闭浏览器就过期
        # 如果cookie 过期时间设置为None 表示关闭浏览器就过期, 如果设置为0, 代表直接删除
        if remembered is None:
            request.session.set_expiry(0)  # 设置session的过期时间为 关闭浏览器就过期

        # request.session.set_expiry(0 if remembered is None else 60 * 60 * 24 * 30)
        # 4. 重定向
        return redirect('/')
        """

    def post(self, request):
        """登录功能逻辑"""
        # 1.接收请求体表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')

        # 2.校验
        # 用户登录认证
        user = authenticate(request, username=username, password=password)
        # 如果登录失败
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 3.状态保持
        login(request, user)

        # 3.1 如果用户没有勾选记住登录
        # 如果session 过期时间设置为None 表示使用默认的14天, 如果设置为0 代表关闭浏览器就过期
        # 如果cookie 过期时间设置为None 表示关闭浏览器就过期, 如果设置为0, 代表直接删除
        if remembered is None:
            request.session.set_expiry(0)  # 设置session的过期时间为 关闭浏览器就过期

        # request.session.set_expiry(0 if remembered is None else 60 * 60 * 24 * 30)
        # 4. 重定向
        next = request.GET.get('next')  # 尝试去获取查询参数中是否有用户界面的来源,如果有来源,登录成功后跳转到来源界面
        response = redirect(next or '/')  # 创建响应对象
        # 给cookie中设置username
        response.set_cookie('username', user.username,
                            max_age=(None if remembered is None else settings.SESSION_COOKIE_AGE))
        # 合并购物车
        merge_cart_cookie_to_redis(request, response)

        return response


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        # 1. 清除状态保持
        logout(request)
        # 2. 清除cookie的username
        response = redirect('/login/')
        response.delete_cookie('username')
        # 3. 重定向到login界面
        return response


# class InfoView(View):
#     """用户中心"""
#
#     def get(self, request):
#         # 如果当前是登录用户直接响应用户中心界面
#         if request.user.is_authenticated:
#             return render(request, 'user_center_info.html')
#         else:
#             return redirect('/login/?next=/info/')


class InfoView(mixins.LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        # 如果当前是登录用户直接响应用户中心界面
        # context = {
        #     'username': request.user.username,
        #     'mobile': request.user.mobile
        # }
        return render(request, 'user_center_info.html')


class EmailView(LoginRequiredView):
    """用户设置邮箱"""

    def put(self, request):
        # 1.接收请求体中的数据 body
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 2.校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('邮箱格式不正确')

        # 3.获取到当前登录的user
        user = request.user
        # 3.1 修改它的email字段
        user.email = email
        user.save()

        # 在此进行对邮箱发送激活邮件
        # from django.core.mail import send_mail
        # send_mail(subject='邮件主题', message='邮件普通内容', from_email='发件人', recipient_list=['收件人'],
        #       html_message='邮件超文本内容')
        # send_mail(subject='美多商城', message='', from_email='美多商城<itcast99@163.com>', recipient_list=[email],
        #       html_message="<a href='http://www.itcast.cn'>传智<a>")
        # verify_url = 'http://www.baidu.com'
        # verify_url = 'http://www.meiduo.site:8000/verify_email?token=dlkfjdlksjfaldksjalkfjdsalkfjdsa'
        verify_url = generate_email_verify_url(user)
        send_verify_url.delay(email, verify_url)
        # 4.响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class VerifyEmailView(View):
    """激活邮箱"""

    def get(self, request):
        # 1.接收查询参数中的token
        token = request.GET.get('token')
        # 2.校验
        if token is None:
            return http.HttpResponseForbidden('缺少token')

        # 3.修改当前user的email_active数据
        user = check_email_verify_url(token)
        if user is None:
            return http.HttpResponseForbidden('token无效')
        user.email_active = True
        user.save()
        # 4.重定向到用户中心
        return redirect('/info/')


class AddressesView(LoginRequiredView):
    """用户收货地址"""

    def get(self, request):
        user = request.user

        # 1.查询当前登录用户的所有未被逻辑删除的收货地址
        address_qs = Address.objects.filter(user=user, is_deleted=False)
        # address_qs = user.addresses.filter(is_delete=False)

        addresses = []  # 用来包装每个收货地址字典
        # 2. 遍历查询集中每个address模型转换成字典 并包装到列表中
        for address in address_qs:
            addresses.append(
                {
                    'id': address.id,
                    'title': address.title,
                    'receiver': address.receiver,
                    'province_id': address.province_id,
                    'province': address.province.name,
                    'city_id': address.city_id,
                    'city': address.city.name,
                    'district_id': address.district_id,
                    'district': address.district.name,
                    'place': address.place,
                    'mobile': address.mobile,
                    'tel': address.tel,
                    'email': address.email,
                }
            )

        context = {
            'addresses': addresses,  # '当前登录用户的所有收货地址列表',
            'default_address_id': user.default_address_id  # 获取当前用户的默认收货地址id
        }
        return render(request, 'user_center_site.html', context)


class CreateAddressView(LoginRequiredView):
    """收货地址新增"""

    def post(self, request):
        user = request.user
        # 0.查询当前用户收货地址数量
        count = Address.objects.filter(user=user, is_deleted=False).count()
        if count >= 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '收货地址数量超过上限'})

        # 1.接收请求体的非表单 body
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2.校验
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 3. 创建Address模型对象 并save
        try:
            address = Address.objects.create(
                user=user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except DatabaseError as e:
            logger.error(e)
            return http.HttpResponseForbidden('收货地址数据有误')

        # 如果当前用户还没有默认收货地址,就将当前新增的收货地址设置为默认地址
        if user.default_address is None:
            user.default_address = address
            user.default_address.save()  # 修改之后保存

        # 将新增的收货地址模型对象转换成字典响应给前端
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }

        # 4.响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增收货地址成功', 'address': address_dict})


class UpdateDestroyAddressView(LoginRequiredView):
    """收货地址修改和删除"""

    def put(self, request, address_id):

        # 校验要修改的收货地址是否存在
        try:
            address = Address.objects.get(id=address_id, user=request.user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id不存在')

        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2.校验
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 3. 修改Address模型对象
        try:
            Address.objects.filter(id=address_id).update(
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except DatabaseError as e:
            logger.error(e)
            return http.HttpResponseForbidden('收货地址数据有误')
        #
        # 用update方式修改数据时, 数据库用来记录更新时间的字段不会重新赋值
        # address.title = title
        # # .....
        # address.save()
        # 重新从数据库查询修改后的收货地址
        address = Address.objects.get(id=address_id)
        # 将修改后的收货地址模型对象转换成字典响应给前端
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }

        # 4.响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改收货地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除指定收货地址"""

        # 校验
        try:
            address = Address.objects.get(id=address_id, user=request.user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id不存在')

        # 修改
        address.is_deleted = True
        address.save()

        # address.delete()

        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredView):
    """设置默认收货地址"""

    def put(self, request, address_id):
        # 校验要修改的收货地址是否存在
        try:
            address = Address.objects.get(id=address_id, user=request.user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id不存在')
        # 获取当前user
        user = request.user
        user.default_address = address
        user.save()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginRequiredView):
    """修改收货地址标题"""

    def put(self, request, address_id):
        # 校验要修改的收货地址是否存在
        try:
            address = Address.objects.get(id=address_id, user=request.user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id不存在')

        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        if title is None:
            return http.HttpResponseForbidden('缺少必传参数')

        address.title = title
        address.save()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改收货地址标题成功'})


# 列表视图(查询所有, 新增)    # 详情视图(查询单一, 修改, 删除)
#  get post /books/        # get  put  delete books/pk/


class ChangePasswordView(LoginRequiredView):
    """修改用户密码"""

    def get(self, request):
        return render(request, 'user_center_pass.html')

    def post(self, request):
        # 1.接收表单数据
        query_dict = request.POST
        old_pwd = query_dict.get('old_pwd')
        new_pwd = query_dict.get('new_pwd')
        new_cpwd = query_dict.get('new_cpwd')

        # 校验
        if all([old_pwd, new_pwd, new_cpwd]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        user = request.user
        if user.check_password(old_pwd) is False:
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_pwd):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        # 修改当前登录用户的set_password
        user.set_password(new_pwd)
        user.save()

        # 让用户重新登录
        # return redirect('/logout/')
        logout(request)
        response = redirect('/login/')
        response.delete_cookie('username')
        return response


class UserBrowseHistories(View):
    """保存用户浏览记录"""

    def post(self, request):
        user = request.user
        if not user.is_authenticated:
            # 如果用户未登录,提前响应
            return http.JsonResponse({"code": RETCODE.SESSIONERR, 'errmsg': '用户未登录'})

        # 1.接收sku_id
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 2.校验
        try:
            sku = SKU.objects.get(id=sku_id, is_launched=True)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')

        # 3.创建redis连接对象
        redis_conn = get_redis_connection('history')
        key = 'history_%s' % user.id
        pl = redis_conn.pipeline()
        # 3.1 先去重  lrem
        pl.lrem(key, 0, sku_id)
        # 3.2 添加到列表开头 lpush
        pl.lpush(key, sku_id)
        # 3.3 截取列表中前5个元素,  ltrim
        pl.ltrim(key, 0, 4)
        # 执行管道
        pl.execute()

        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self, request):
        user = request.user

        if not user.is_authenticated:
            # 如果用户未登录,提前响应
            return http.JsonResponse({"code": RETCODE.SESSIONERR, 'errmsg': '用户未登录'})

        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 获取当前用户在redis中存储的浏览记录list
        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, -1)
        sku_list = []  # 用来包装所有sku字典
        # 根据sku_id查询到对应的sku模型
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            # 将sku模型转换成字典
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })

        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': sku_list})



